import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { masterService } from '../../lib/master.service';
import { saveVarService } from '../../lib/saveVar.service';
import { path } from '../path.config';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css'],
    providers: [masterService]
})

export class LoginComponent implements OnInit {
    public bgImg = ['https://wochu.oss-cn-hangzhou.aliyuncs.com/upload/a25a3819-e777-416b-a215-74dd1f25915f.jpg',
        'https://wochu.oss-cn-hangzhou.aliyuncs.com/upload/d30531b1-22d3-4421-9178-8e98b58f897a.jpg'];
    public loginImg = '';
    public isUsername: boolean = false;
    public isPassword: boolean = false;
    public errorMsg: any = "";
    loginModel = {
        username: '',
        password: ''
    }
    // 登录接口
    public loginPath: any = path.login.apiUrl;

    constructor(public _masterService: masterService,
        private _router: Router,
        public _saveVarService: saveVarService) { }

    ngOnInit() {
        //   登录页随机背景图片
        let index = Math.round(Math.random());
        this.loginImg = this.bgImg[index];
    }

    public keyEnterLogin(event) {
        if (event.keyCode == 13) {
            this.login();
        }
    }
    // 登录
    login() {
        if (this.loginModel.username == '' || this.loginModel.password == '') {
            this.errorMsg = "请输入账户或者密码";
            return;
        } else {
            this.errorMsg = "";
        }
        this._masterService
            .postLoginData(this.loginPath, this.loginModel)
            .subscribe((res) => {
                res = res.json();
                if (res.access_token) {
                    let time = new Date().getTime();
                    localStorage.setItem("access_token", res.access_token);
                    localStorage.setItem("alias", res.alias);
                    localStorage.setItem("expires", '' + time);
                    this.errorMsg = "";
                    this._router.navigate(['/main']);
                }
            }, (err) => {
                if (err.status == 400) {
                    this.errorMsg = "账户名或者密码错误";
                    this.loginModel = {
                        username: '',
                        password: ''
                    }
                }
            })
    }
}
